import IconDouyin from '@/components/icon/IconDouyin';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeibo from '@/components/icon/IconWeibo';
import { saveTophubOperate } from '@/services/api/api-tophub-operate';
import {
  ActionType,
  DrawerForm,
  ProFormInstance,
  ProList,
  ProTable,
} from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Button, Flex, message, Space, Tag, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import UploadDragger from '../components/UploadDragger';
import AddOperateAssociationEdit from './AddOperateAssociationEdit';
interface AddOperateAssociationProps {
  selectHotQuerys: TophubHotRankData.HotQuery[];
  onOpenChange: (visible: boolean) => void;
  onRefurbish: () => void;
}

const AddOperateAssociation: React.FC<AddOperateAssociationProps> = ({
  selectHotQuerys,
  onOpenChange,
  onRefurbish,
}) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [datas, setDatasState] = useState<TophubHotRankData.HotQuery[]>(selectHotQuerys);

  useEffect(() => {
    setDatasState(selectHotQuerys);
  }, [selectHotQuerys]);

  return (
    <DrawerForm
      title="关联词条"
      trigger={<Button type="primary">关联</Button>}
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
        width: 800,
      }}
      formRef={formRef}
      onOpenChange={async (visible) => {
        if (visible) {
        } else {
          setDatasState([]);
        }
      }}
      onValuesChange={(values) => {}}
      submitter={{
        resetButtonProps: {
          type: 'primary',
          danger: true,
        },
      }}
      onFinish={async (values) => {
        for (let i = 0; i < datas.length; i++) {
          const data = datas[i];
          const addSources = data.addSources;

          if (addSources == null || addSources.length == 0) {
            message.warning(`请给“${data.name}”添加关联账号`);
            return;
          }
        }

        const response = await saveTophubOperate({
          insertType: 1,
          recordType: 1,
          associations: datas?.map((item) => {
            return {
              hotId: item.id,
              sourceIds: item.addSources
                ?.map((item) => item[item.length - 1])
                .map((item) => {
                  return item.value;
                }),
              remarks: item.remarks,
              attachmentIds: item?.attachments?.map((item) => {
                return { id: item.response.data.id };
              }),
            };
          }),
        });

        if (response.code == 0) {
          message.success('关联成功！');
          onOpenChange(false);
          return true;
        }
      }}
    >
      <ProTable<TophubHotRankData.HotQuery>
        columns={[
          {
            title: (
              <span
                style={{
                  color: '#99a3b7',
                  fontSize: 12,
                  textAlign: 'center',
                  fontWeight: 'normal',
                }}
              >
                热点
              </span>
            ),
            dataIndex: 'name',
            align: 'center',
            copyable: true,
            ellipsis: true,
            width: '45%',
            render: (dom, entity, index, action) => <>{entity.name}</>,
          },
          {
            title: (
              <span
                style={{
                  color: '#99a3b7',
                  fontSize: 12,
                  textAlign: 'center',
                  fontWeight: 'normal',
                }}
              >
                排名
              </span>
            ),
            dataIndex: 'topIndex',
            align: 'center',
          },
          {
            title: (
              <span
                style={{
                  color: '#99a3b7',
                  fontSize: 12,
                  textAlign: 'center',
                  fontWeight: 'normal',
                }}
              >
                渠道
              </span>
            ),
            dataIndex: 'type',
            align: 'center',
            valueEnum: {
              1: { text: '微博' },
              2: { text: '抖音' },
              4: { text: '今日头条' },
            },
          },
          {
            title: (
              <span
                style={{
                  color: '#99a3b7',
                  fontSize: 12,
                  textAlign: 'center',
                  fontWeight: 'normal',
                }}
              >
                范围
              </span>
            ),
            dataIndex: 'isCity',
            align: 'center',
            valueEnum: {
              0: { text: '全国' },
              1: { text: '重庆' },
            },
          },
          {
            title: (
              <span
                style={{
                  color: '#99a3b7',
                  fontSize: 12,
                  textAlign: 'center',
                  fontWeight: 'normal',
                }}
              >
                媒体
              </span>
            ),
            dataIndex: 'author',
            align: 'center',
            render: (dom, entity, index, action) => entity.author,
          },
          {},
        ]}
        actionRef={actionRef}
        rowKey="id"
        defaultSize={'small'}
        search={false}
        options={false}
        pagination={false}
        ghost
        dataSource={datas}
      />

      <ProList<TophubHotRankData.HotQuery>
        style={{
          marginTop: 25,
        }}
        ghost
        pagination={false}
        actionRef={actionRef}
        rowKey="id"
        showActions="hover"
        grid={{ gutter: 16, column: 1 }}
        itemCardProps={{
          bodyStyle: {
            paddingLeft: 12,
            paddingBottom: 12,
            paddingRight: 12,
            paddingTop: 0,
          },
        }}
        dataSource={datas}
        metas={{
          title: {
            render: (text, row, index) => {
              let hotRankType;

              if (row.type == 1) {
                hotRankType = {
                  icon: <IconWeibo width={18} height={21} />,
                  name: '微博热搜',
                };
              } else if (row.type == 2) {
                hotRankType = {
                  icon: <IconDouyin width={18} height={21} />,
                  name: '抖音热榜',
                };
              } else if (row.type == 4) {
                hotRankType = {
                  icon: <IconToutiao width={18} height={21} />,
                  name: '头条热搜',
                };
              }

              return (
                <>
                  <Space align="start">
                    <Space align={'start'}>{hotRankType?.icon}</Space>
                    <Tag color={row?.isCity == 0 ? 'error' : 'gold'}>
                      {row?.isCity == 0 ? '全国' : '重庆'}：{row.topIndex}
                    </Tag>
                    <Typography.Title copyable level={5}>
                      <a>{row.name}</a>
                    </Typography.Title>
                  </Space>
                </>
              );
            },
          },
          content: {
            render: (text, row, index) => {
              let authorTitle;

              if (row.type == 1) {
                authorTitle = '主持人';
              } else if (row.type == 2) {
                authorTitle = '作者';
              } else if (row.type == 4) {
                authorTitle = '作者';
              }

              return (
                <div
                  style={{
                    width: '100%',
                  }}
                >
                  <Flex justify={'space-between'} align={'center'}>
                    <Space align={'start'} size="large">
                      <span>
                        <Typography.Text type="secondary">{authorTitle}：</Typography.Text>
                        {row?.author ? row?.author : '暂无'}
                      </span>
                      <span>
                        <Typography.Text type="secondary">采录时间：</Typography.Text>
                        {row?.insertTime}
                      </span>
                    </Space>
                    <a href={row?.url} target="_blank">
                      原文链接
                    </a>
                  </Flex>
                  {row?.sources && (
                    <div
                      style={{
                        marginTop: 10,
                      }}
                    >
                      <Typography.Text type="secondary">关联账号：</Typography.Text>
                      {row?.sources?.length > 0 && (
                        <Space size={[4, 8]} wrap>
                          {row?.sources?.map((item) => (
                            <Tag>{item.label}</Tag>
                          ))}
                        </Space>
                      )}
                    </div>
                  )}

                  {row?.addSources && (
                    <div
                      style={{
                        marginTop: 10,
                      }}
                    >
                      <Typography.Text type="secondary">新增关联账号：</Typography.Text>
                      {row?.addSources?.length > 0 && (
                        <Space size={[4, 8]} wrap>
                          {row?.addSources
                            ?.map((item) => item[item.length - 1])
                            .map((item) => {
                              return <Tag>{item.label}</Tag>;
                            })}
                        </Space>
                      )}
                    </div>
                  )}

                  {row?.remarks && (
                    <div
                      style={{
                        marginTop: 10,
                      }}
                    >
                      <Typography.Paragraph>
                        <blockquote>备注：{row?.remarks}</blockquote>
                      </Typography.Paragraph>
                    </div>
                  )}

                  {row?.attachments && (
                    <div
                      style={{
                        marginTop: 10,
                      }}
                    >
                      <UploadDragger
                        value={row?.attachments}
                        dragger={false}
                        onPreview={(file) => {}}
                        url="/tophub/attachment/save"
                        maxCount={10}
                      />
                    </div>
                  )}
                </div>
              );
            },
          },
          actions: {
            render: (text, row, index) => {
              return (
                <AddOperateAssociationEdit
                  selectHotQuery={row}
                  onRefurbish={(values: any) => {
                    setDatasState(
                      datas.map((item) => {
                        if (item.id == values.hotId) {
                          return {
                            ...item,
                            ...values,
                          };
                        } else {
                          return item;
                        }
                      }),
                    );
                    actionRef.current?.reloadAndRest();
                    return true;
                  }}
                />
              );
            },
          },
        }}
      />
    </DrawerForm>
  );
};
export default AddOperateAssociation;
